<?php

// start session
session_name('cms_session');
session_start();

if(isset($_SESSION['error'])) {
    $now = strtotime('-1 minute');

    // check for next try
    if($now > $_SESSION['error']) {
        unset($_SESSION['error']);
    }
    else {
        echo file_get_contents('template/error_page.html');
        exit();
    }
}

/************************************************************
 *                  FUNCTIONS
 ***********************************************************/

/**
 * writes error log
 */
function write_errorlog($message,$level,$source,$inFile='') {
    global $MySQL_DB;

    if($GLOBALS['develop'] == 1) {
        echo "ERROR MESSAGE: ".$message."; LEVEL: ".$level.";  SOURCE: ".$source.";";
    }
    else {
        $now = date("Y-m-d H:i:s");
        if($inFile == '') {
            $result_query = execute_query("INSERT INTO %PRE%logging (datetime, source, message, level) VALUES ('".$now."', '".$source."', '".$message."', '".$level."')",$MySQL_DB);
        }
        else {
            $filename = "Errorlog_".date("Y-m").".txt";
            $file = fopen("log/".$filename,"a");

            $errormessage = $now.": ".$message."; LEVEL: ".$level."; SOURCE: ".$source."; \n";
            fwrite($file, $errormessage);
            fclose($file);
        }

        // display error page
        if($level <= 2) {
            $_SESSION['error'] = strtotime('now');
            header('Location: index.php');
        }
    }
}

/**
 * execute mysqli query with error handling
 *
 * @return resultset
 */
function execute_query($query,$db) {
    // replace database prefix
    global $db_prefix;
    $query = str_replace('%PRE%', $db_prefix, $query);

    $result_query = $db->query($query) or die(write_errorlog("MySQL Message: ".mysql_error()."; QUERY: ".$query,2,"MySQL Error",1));

    return $result_query;
}

/**
 * return current url
 *
 * @return String
 */
function getCurrentURL() {

    $url = $_SERVER['PHP_SELF'];
    $gets = http_build_query ($_GET);
    if(strlen($gets) > 0) {
        $url = $url.'?'.$gets;
    }

    return $url;
}

?>